package com.example.movie.ui.movie

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.constants.Constants
import com.example.movie.common.constants.RequestCode
import com.example.movie.data.movie.factory.MovieDetailViewModelFactory
import com.example.movie.data.movie.model.MovieDetailViewModel
import com.example.movie.data.user.login.model.SharedLoginViewModel
import com.example.movie.ui.MainActivity
import com.example.movie.ui.home.tabs.model.ActorInfo
import com.example.movie.ui.movie.adapter.ActorListAdapter
import com.example.movie.ui.movie.adapter.MovieDetailBottomPagerAdapter
import com.example.movie.ui.user.auth.LoginActivity
import com.example.movie.utils.ContextHolder
import com.google.android.material.appbar.AppBarLayout
import kotlinx.android.synthetic.main.fragment_movie_detail.*
import kotlinx.android.synthetic.main.fragment_movie_detail.toolbar
import kotlinx.android.synthetic.main.fragment_movie_detail.view.*
import kotlinx.android.synthetic.main.fragment_person_page.*
import java.util.*
import kotlin.math.abs

class MovieDetailActivity : AppCompatActivity() {

    private var isShowBtn: Boolean = true
    private var hopeLook: Boolean = false
    private var hasSeen: Boolean = false

    private val movieDetailViewModel: MovieDetailViewModel by viewModels(factoryProducer = { MovieDetailViewModelFactory() })
    private val loginViewModel: SharedLoginViewModel =
        ContextHolder.from(MainActivity::class).loginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //防止控件被输入法挤到变形
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        setContentView(R.layout.fragment_movie_detail)
        loadData()
        setObservers()
        initView()
    }

    @SuppressLint("SetTextI18n")
    private fun setObservers() {
        movieDetailViewModel.movieDetailData.observe(this, { it ->
            it?.success?.let { it ->
                it.movieVo?.let {
                    with(it) {
                        movie_name.text = movieName
                        movie_outline.text =
                            "$movieTypeName $areaName\n$registerTime"
                        star.rating = score
                        movie_detail.text = content
                        movie_title.text = movieName.toString()

                        Glide
                            .with(this@MovieDetailActivity)
                            .load(AppConstants.STATIC_SOURCE_URL + cimg)
                            .placeholder(R.mipmap.logo)
                            .error(R.drawable.error)
                            .into(movie_img)
                    }
                }

                it.actorTypeBeanVos?.let {
                    val items = mutableListOf<ActorInfo>()
                    repeat(it.size) { idx ->
                        it[idx].apply {
                            repeat(actorList.size) { idx ->
                                actorList[idx].apply {
                                    items.add(ActorInfo(cimg, actorTypeName, actorName))
                                }
                            }
                        }
                    }

                    val baseAdaptor = ActorListAdapter(items)
                    actors_list.adapter = baseAdaptor
                    baseAdaptor.notifyDataSetChanged()
                }

                it.haveHopeLook.let {
                    if (it) {
                        hopeLook = true;
                        hopeLook_layout.wantSee.setImageResource(R.drawable.heart_red)
                    }
                }

                it.haveSeenBefore.let {
                    if (it) {
                        hasSeen = true;
                        have_seen_layout.seen.setImageResource(R.drawable.approve_red)
                    }
                }

            }

        })

        movieDetailViewModel.approveState.observe(this, {
            it.success?.let {
                with(hopeLook_layout.wantSee as ImageView) {
                    hopeLook = if (hopeLook) {
                        setImageResource(R.drawable.heart_white)
                        false
                    } else {
                        setImageResource(R.drawable.heart_red)
                        true
                    }
                }
            }

        })
        movieDetailViewModel.haveSeenState.observe(this, {
            it.success?.let {
                with(have_seen_layout.seen as ImageView) {
                    hasSeen = if (hasSeen) {
                        setImageResource(R.drawable.approve_white)
                        false
                    } else {
                        setImageResource(R.drawable.approve_red)
                        true
                    }
                }
            }

        })

    }

    @SuppressLint("SetTextI18n")
    private fun loadData() {
        intent?.extras?.getInt("movieId")?.let {
            movieDetailViewModel.loadMovieDetailData(it)
        }
    }

    private fun initView() {
        actors_list.apply {
            this.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            //设置演员列表间距
            this.addItemDecoration(object : RecyclerView.ItemDecoration() {
                private val space: Int = 15
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.left = space
                    outRect.right = space
                    outRect.bottom = space
                    outRect.top = space
                }
            })
        }

        val clickListener = View.OnClickListener {
            if (isShowBtn) {
                more.setImageResource(R.drawable.comon_wihte_less)
                //展开文字
                val layoutParams = movie_detail.layoutParams
                layoutParams.height = ConstraintLayout.LayoutParams.WRAP_CONTENT
                movie_detail.layoutParams = layoutParams
                hint.text = "收起"
                isShowBtn = false;
            } else {
                isShowBtn = true;
                hint.text = "展开"
                //收起文字
                val layoutParams = movie_detail.layoutParams
                layoutParams.height = 210
                movie_detail.layoutParams = layoutParams
                more.setImageResource(R.drawable.common_white_more)
            }
        }
        more.setOnClickListener(clickListener)
        hint.setOnClickListener(clickListener)

        hopeLook_layout.setOnClickListener { it ->
            if (loginViewModel.isLoggedIn()) {
                intent?.extras?.getInt("movieId")?.let {
                    movieDetailViewModel.changeState(it, Constants.UserMovieTab.HOPE_LOOK)
                }
            } else {
                startActivityForResult(
                    Intent(this, LoginActivity::class.java),
                    RequestCode.NEED_LOGIN
                )
            }
        }

        have_seen_layout.setOnClickListener { it ->
            if (loginViewModel.isLoggedIn()) {
                intent?.extras?.getInt("movieId")?.let {
                    movieDetailViewModel.changeState(it, Constants.UserMovieTab.HAVE_SEEN)
                }
            } else {
                startActivityForResult(
                    Intent(this, LoginActivity::class.java),
                    RequestCode.NEED_LOGIN
                )
            }
        }

        back.setOnClickListener {
            onBackPressed()
        }

        movie_detail_view_paper.adapter =
            MovieDetailBottomPagerAdapter(this, supportFragmentManager)
        movie_detail_tabs.setupWithViewPager(movie_detail_view_paper)

        movie_app_bar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _: AppBarLayout, verticalOffset: Int ->
            if (verticalOffset == 0) {
                movie_hint.visibility = View.VISIBLE
            } else {
                movie_hint.visibility = View.GONE
            }
            toolbar.transitionAlpha = (abs(verticalOffset * 1.0) / toolbar.height).toFloat()
            toolbar.background.alpha = ((abs(verticalOffset * 1.0) / toolbar.height).toFloat() * 20).toInt()
        })

    }


}